package com.example.pathviewdemo.widget;

import android.content.Context;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.Path;
import android.graphics.RectF;
import android.util.AttributeSet;
import android.util.Log;
import android.view.MotionEvent;
import android.view.View;

import androidx.annotation.Nullable;
import androidx.core.graphics.PathParser;

import com.example.pathviewdemo.R;

import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.NodeList;

import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;

/**
 * 中国地图。
 */
public class ChinaMapView extends View {
    String TAG = ChinaMapView.class.getSimpleName();
    List<MapChildCanvas> childCanvas=new ArrayList<>();
    private Paint paint;
    int [] colors={Color.BLUE,Color.RED,Color.GREEN,Color.YELLOW,Color.BLACK};
    float scale=1.0f;
    private RectF viewRectF;
    MapChildCanvas selectCanvas=null;
    public ChinaMapView(Context context) {
        this(context, null);
    }

    public ChinaMapView(Context context, @Nullable AttributeSet attrs) {
        this(context, attrs, -1);
    }

    public ChinaMapView(Context context, @Nullable AttributeSet attrs, int defStyleAttr) {
        this(context, attrs, defStyleAttr, -1);

    }

    public ChinaMapView(Context context, @Nullable AttributeSet attrs, int defStyleAttr, int defStyleRes) {
        super(context, attrs, defStyleAttr, defStyleRes);
        initView();
    }

    /**
     * 初始化view
     */
    private void initView() {
        paint = new Paint();
        thread.start();
    }

    Thread thread = new Thread(new Runnable() {



        @Override
        public void run() {
            //获取到输入流。
            InputStream inputStream = getResources().openRawResource(R.raw.china);
            DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
            DocumentBuilder builder = null;
            childCanvas.clear();
            try {
                builder = factory.newDocumentBuilder();
                Document document = builder.parse(inputStream);
                //获取节点
                Element element = document.getDocumentElement();
                NodeList pathElements = element.getElementsByTagName("path");
                float left=-1;
                float bottom=-1;
                float right=-1;
                float top=-1;
                // 获取节点
                for (int i = 0; i < pathElements.getLength(); i++) {
                    // 获取path 节点
                    Element item = (Element) pathElements.item(i);
                    String path = item.getAttribute("d");
                    String title = item.getAttribute("title");
                    String id = item.getAttribute("id");
                    Log.d(TAG, "run: " + title + "  " + id);
                    //转换为显示 路径
                    Path pathData = PathParser.createPathFromPathData(path);
                    // 获取到路径的边界,这个主要是获取需要绘制的区域。
                    RectF rectF=new RectF();
                    pathData.computeBounds(rectF,true);
                    // 将值扩展到最外层 view
                    left=left==-1?rectF.left:Math.min(rectF.left,left);
                    bottom=bottom==-1?rectF.bottom:Math.max(rectF.bottom,bottom);
                    right=right==-1?rectF.right:Math.max(rectF.right,right);
                    top=top==-1?rectF.top:Math.min(rectF.top,top);
                    // 子类 赋值
                    MapChildCanvas canvas=new MapChildCanvas(pathData);
                    canvas.setId(id);
                    canvas.setCityName(title);
                    canvas.setDrawColor(colors[i%colors.length]);
                    childCanvas.add(canvas);
                }
                // 发送重新测量
                viewRectF = new RectF(left,top,right,bottom);
                measure(getMeasuredWidth(),getMeasuredHeight());
                postInvalidate();

            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    });


    @Override
    protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
        super.onMeasure(widthMeasureSpec, heightMeasureSpec);

        if (viewRectF!=null){
            int width = MeasureSpec.getSize(widthMeasureSpec);
            scale=(float)width/(viewRectF.width());
        }
    }

    @Override
    protected void onDraw(Canvas canvas) {
        super.onDraw(canvas);
        canvas.save();
        canvas.scale(scale,scale);
        for (MapChildCanvas mapChildCanvas: childCanvas){
            mapChildCanvas.onChildDraw(canvas,paint,mapChildCanvas==selectCanvas);
            canvas.save();
        }
    }

    @Override
    public boolean onTouchEvent(MotionEvent event) {
        getSelectMap(event.getX(),event.getY());
        return super.onTouchEvent(event);
    }

    /**
     * 获取选中的城市
     * @param x
     * @param y
     */
    private void getSelectMap(float x, float y) {
        for (MapChildCanvas canvas: childCanvas){
            if (canvas.isTouch(x/scale, y/scale)){
                selectCanvas=canvas;
                postInvalidate();
            }
        }
    }
}
